// pages/Orders/Transaction/Transaction.js
//获取应用实例
const app = getApp();
import { getOrderForm , getOrderTypeEnums , getOrderTypeClassify } from '../../../api/earning';
import { getBrandConfig } from '../../../api/brand';
import { throttle , formatTime } from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    page: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    dataList: [],
    orderTypeAllList: [], // 所有类型
    orderTypeList: [],
    disburse: [], // 支出类型
    statusList: [{ id: '4', name: '待到账',},{ id: '1', name: '已成功',}],
    show: false,
    monthDate: '',
    orderStatus: '',
    orderType: '',
    minDate: new Date('2023-03-01').getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    showTime: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getOrderTypeEnums();
    // this._getOrderTypeClassify();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      orderType: '',
      orderStatus: '',
      monthDate: '',
    })
    this._getOrderForm();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    console.log(this.data.isReachBottom,'isReachBottom')
    if(this.data.isReachBottom){
      this._getOrderForm()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取交易订单类型
  _getOrderTypeEnums(){
    let _this = this;
    getOrderTypeEnums()
    .then(res => {
      if(res.success){
        _this.setData({
          orderTypeAllList: res.data,
        })
        _this._getBrandConfig();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取品牌订单类型配置
  _getBrandConfig(){
    let _this = this;
    getBrandConfig({})
    .then(res => {
      if(res.success){
        var brandDISBURSEOrderTypes = [];
        var brandOrderTypes = [];
        var brandDISBURSEOrderTypesArr = [];
        var brandOrderTypesArr = [];
        if(res.data.length > 0){
          brandDISBURSEOrderTypesArr = res.data[0].brandDISBURSEOrderTypes ? res.data[0].brandDISBURSEOrderTypes.split(',') : [];
          brandOrderTypesArr = res.data[0].brandOrderTypes ? res.data[0].brandOrderTypes.split(',') : [];
        }
        for (let index = 0; index < _this.data.orderTypeAllList.length; index++) {
          const item = _this.data.orderTypeAllList[index];
          for (let index = 0; index < brandOrderTypesArr.length; index++) {
            const types = brandOrderTypesArr[index];
            if(types == item.orderType){
              brandOrderTypes.push(item);
            }
          }
        }
        for (let index = 0; index < brandDISBURSEOrderTypesArr.length; index++) {
          const element = brandDISBURSEOrderTypesArr[index];
          const item = parseInt(element);
          brandDISBURSEOrderTypes.push(item);
        }
        _this.setData({
          orderTypeList: brandOrderTypes,
          disburse: brandDISBURSEOrderTypes,
        })
        console.log(_this.data.disburse,'brandDISBURSEOrderTypes')
        _this._getOrderForm();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取交易订单类型分类
  _getOrderTypeClassify(){
    let _this = this;
    getOrderTypeClassify()
    .then(res => {
      if(res.success){
        _this.setData({
          disburse: res.data.orderType,
        })
        _this._getOrderForm();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取交易明细
  _getOrderForm(){
    let _this = this;
    getOrderForm({page: _this.data.page,orderStatus: _this.data.orderStatus,orderType: _this.data.orderType,monthDate: _this.data.monthDate})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        if(_this.data.page == 0){
          list = res.data.content.map(item => {
            if(_this.data.disburse.indexOf(item.orderType) != -1){
              item.addOrSub = '4';
            }else{
              item.addOrSub = '0';
            }
            return item;
          });
        }else{
          var arr = res.data.content.map(item => {
            if(_this.data.disburse.indexOf(item.orderType) != -1){
              item.addOrSub = '4';
            }else{
              item.addOrSub = '0';
            }
            return item;
          })
          list = list.concat(arr);
          console.log(list,'list');
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 展示筛选条件
  showSel(){
    this.setData({show: true})
  },
  onClose() {
    this.setData({ show: false });
  },
  // 重置
  reset(){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      orderType: '',
      orderStatus: '',
      monthDate: '',
      show: false,
    })
    this._getOrderForm();
  },
  // 确认
  submit(){
    this.setData({
      show: false,
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._getOrderForm();
  },
  // 选择类型
  selType(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item,'item')
    this.setData({
      orderType: item.orderType
    })
  },
  // 选择状态
  selStatus(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item,'item')
    this.setData({
      orderStatus: item.id
    })
  },
  showSelTime(){
    this.setData({showTime: true,})
  },
  confirm(event) {
    console.log(event)
    var monthDate = formatTime(new Date(event.detail),'Y-M');
    console.log(monthDate,'monthDate')
    this.setData({
      monthDate: monthDate,
      showTime: false,
    });
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
})